#!/bin/bash -x


VERSION="1.0.22"
DESTDIR="/opt"
DSDIR="$DESTDIR/usr/share/debootstrap"
TMPDIR="/tmp/installdebootstrap"
TMPDEBOOTSTRAPSRC="$TMPDIR/debootstrap-$VERSION"
URLDWL="http://ftp.de.debian.org/debian/pool/main/d/debootstrap/debootstrap_$VERSION.tar.gz"

initTmpDir() {
	if [ -d $TMPDIR ]
	then
		echo "-> Purge de $TMPDIR" 
		rm -rf $TMPDIR
		echo "-> Create $TMPDIR"
		mkdir -p $TMPDIR
	else
		echo "-> $TMPDIR dosent exist."
		echo "-> Create $TMPDIR"
		mkdir -p $TMPDIR
	fi
	wget -c --progress=bar -P $TMPDIR $URLDWL
	tar -C $TMPDIR -zxvf "$TMPDIR/debootstrap_$VERSION.tar.gz"
}

createDevicesArchive() {

	TMPDEV="$TMPDEBOOTSTRAPSRC/dev"
	
	if [ -e "$TMPDEV/devices.tar.gz" ]
	then
		echo "-> I delete old devices.tar.gz"
		rm "$TMPDEV/devices.tar.gz"
	fi

	echo "-> Create temporary dev in $TMPDEV"
	rm -rf $TMPDEV
	mkdir -p $TMPDEV
	chown 0:0 $TMPDEV
	chmod 755 $TMPDEV
	echo "-> Makedev"
	(cd $TMPDEV && /sbin/MAKEDEV std ptmx fd consoleonly)
	echo "-> Create devices.tar.gz"
	cd $TMPDEBOOTSTRAPSRC
	tar cf - dev | gzip -9 > "$TMPDEBOOTSTRAPSRC/devices.tar.gz"
	cd
	echo "-> Remove temporary dev"
	rm -rf $TMPDEV
}

install() {
	rm -rf $DSDIR
	mkdir -p $DSDIR/scripts
	mkdir -p $DESTDIR/usr/sbin

	echo "-> Install debootstrap bin"
	cp $TMPDEBOOTSTRAPSRC/debootstrap $DESTDIR/usr/sbin/
	chown root:root $DESTDIR/usr/sbin/debootstrap
	chmod 0755 $DESTDIR/usr/sbin/debootstrap

	echo "-> Install scripts"
	cp -a $TMPDEBOOTSTRAPSRC/scripts/* $DSDIR/scripts/

	echo "-> Install functions file"
	cp $TMPDEBOOTSTRAPSRC/functions $DSDIR
	chown root:root $DSDIR/functions
	chmod 0644 $DSDIR/functions

	echo "-> Install devices.tar.gz"
	cp $TMPDEBOOTSTRAPSRC/devices.tar.gz $DSDIR
}

echo "Installation de deboostrap ..."
initTmpDir
createDevicesArchive
install

echo "----------------------------------------------------------------"
echo "Execute in shell :" 
echo "    $ export DEBOOTSTRAP_DIR=$DSDIR"
echo "    $ export PATH=$PATH:$DESTDIR/usr/sbin"
echo "----------------------------------------------------------------"
